//
//  AfanUserAccountViewModel.swift
//  weiboOfAfan
//
//  Created by afan on 16/3/24.
//  Copyright © 2016年 阿范. All rights reserved.
//

import UIKit

class AfanUserAccountViewModel: NSObject {
    
    static let shardInstace : AfanUserAccountViewModel = AfanUserAccountViewModel()
    
//    var userAccount: AfanUserAccount?
    
    private override init() {
        super.init()
        userAccount = loadUserAccount()
        print("\(userAccount)")
        
    }
    
    ///是否登录
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    
    ///获取用户信息
    func loadUserInfo(completion:(error : NSError?) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters : [String : AnyObject] = [
            "access_token" : userAccount!.access_token!,
            "uid" : userAccount!.uid!
        ]
        AfanNetWorkTool.sharedInstance.afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in  ///成功回调
            
            //返回的是字典
            let dict = result as? [String : AnyObject]
            
            //给账户的用户名和图片地址保存数据
            self.userAccount?.screen_name = dict?["screen_name"] as?String
            self.userAccount?.avatar_large = dict?["avatar_large"] as? String
            
            //保存到沙盒
            self.saveUserAccount()
            
            }) { (_, error) -> Void in///失败回调
                completion(error: error)
        }
        
    }
    
    
    
    
    
    
    
    
    ///账号路径名
     private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    
    
    ///外界调用的账号
    var userAccount: AfanUserAccount?
    
    
    
    
    
    
    func loadAccessToken(code: String,completion: (error: NSError?) -> ()) {
        // 获取accessToken的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 拼接参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        // 发送请求
        /*
        AFN.POST:
        1.请求的url地址
        2.请求参数
        */
        AfanNetWorkTool.sharedInstance.afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in // 1.NSURLSessionDataTask: task 2.响应结果
            print("result: \(result)")
            
            if let dict = result as? [String : AnyObject]{
                ///将网络返回的账号赋值给属性,别人直接访问属性
                self.userAccount = AfanUserAccount(dict: dict)
                print("sssssssssssssssssssuserAccount:\(self.userAccount)")
                
                
                /// 保存模型到沙盒
                self.saveUserAccount()
                
                ///通知控制器保存完成
                completion(error: nil)
                
            }

            }) { (_, error) -> Void in // 1.task 2.响应失败的原因
                print("请求accesstoken失败 \(error)")
                
                completion(error: error)
        }
    }
    
    /// 保存模型到沙盒
    private func saveUserAccount() {
        if self.userAccount != nil {
            // 有账号才需要保存
//            print("----------------\(userAccount)")
//            print("accountPath: \(accountPath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: self.accountPath)
        }
    }
    
    /// 从沙盒加载数据
    private func loadUserAccount() -> AfanUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? AfanUserAccount
        
        
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("userAccount: \(userAccount)")
            return userAccount
        }
        
        return nil
    }
    
}































